<template>
    <div class="exam-detail">
      <y-header title="考试详情" left-arrow @click-left="onBack" />
      
      <div class="exam-info">
        <div class="exam-header">
          <h3>{{ exam.title }}</h3>
          <van-tag :type="getStatusTagType(exam.status)">{{ getStatusText(exam.status) }}</van-tag>
        </div>
        
        <div class="exam-meta">
          <div class="meta-item">
            <van-icon name="clock-o" /> 
            <span>考试时间：{{ formatDate(exam.startTime) }} ~ {{ formatDate(exam.endTime) }}</span>
          </div>
          <div class="meta-item">
            <van-icon name="award-o" /> 
            <span>总分：{{ exam.totalScore }}分</span>
          </div>
          <div class="meta-item">
            <van-icon name="replay" />
            <span>允许重考：{{ exam.allowRetake ? '是' : '否' }}</span>
          </div>
        </div>
        
        <div class="exam-description">
          <p>{{ exam.description }}</p>
        </div>
      </div>
      
      <div class="section-divider">
        <div class="divider-title">题目管理</div>
        <van-button size="small" type="primary" icon="plus" @click="showCreateQuestion = true">添加题目</van-button>
      </div>
      
      <van-empty v-if="questions.length === 0" description="暂无题目" />
      
      <div v-else class="question-list">
        <van-swipe-cell v-for="(question, index) in questions" :key="question.id">
          <van-cell-group inset>
            <van-cell :title="`${index + 1}. ${question.title}`">
              <template #label>
                <div class="question-type">
                  <van-tag plain type="primary">{{ getQuestionTypeText(question.type) }}</van-tag>
                  <span class="question-score">{{ question.score }}分</span>
                </div>
              </template>
            </van-cell>
            
            <!-- 显示问题内容 -->
            <van-cell v-if="question.type === 'choice'">
              <template #title>
                <div class="question-options">
                  <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                    <span class="option-label">{{ String.fromCharCode(65 + optIndex) }}.</span>
                    <span class="option-content">{{ option }}</span>
                  </div>
                </div>
              </template>
            </van-cell>
            
            <van-cell title="正确答案">
              <template #value>
                <div>
                  <template v-if="question.type === 'choice'">
                    <span v-if="Array.isArray(question.answer)">
                      {{ question.answer.map(i => String.fromCharCode(65 + Number(i))).join(', ') }}
                    </span>
                    <span v-else>
                      {{ String.fromCharCode(65 + Number(question.answer)) }}
                    </span>
                  </template>
                  <template v-else-if="question.type === 'text'">
                    {{ question.answer }}
                  </template>
                  <template v-else-if="question.type === 'true_false'">
                    {{ question.answer ? '正确' : '错误' }}
                  </template>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
          
          <template #right>
            <van-button square type="warning" text="编辑" @click="editQuestion(question)" />
            <van-button square type="danger" text="删除" @click="confirmDeleteQuestion(question)" />
          </template>
        </van-swipe-cell>
      </div>
      
      <!-- 创建/编辑题目弹窗 -->
      <van-dialog
        v-model:show="showCreateQuestion"
        :title="isEditingQuestion ? '编辑题目' : '新建题目'"
        show-cancel-button
        :confirmButtonText="isEditingQuestion ? '保存' : '添加'"
        @confirm="saveQuestion"
      >
        <van-form>
          <van-field
            v-model="questionForm.title"
            name="title"
            label="题目"
            type="textarea"
            rows="2"
            placeholder="请输入题目内容"
            :rules="[{ required: true, message: '请输入题目内容' }]"
          />
          
          <van-field
            v-model.number="questionForm.score"
            name="score"
            label="分值"
            type="digit"
            placeholder="请输入分值"
            :rules="[{ required: true, message: '请输入分值' }]"
          />
          
          <van-field name="type" label="题目类型">
            <template #input>
              <van-radio-group v-model="questionForm.type" direction="horizontal">
                <van-radio name="choice">选择题</van-radio>
                <van-radio name="text">填空题</van-radio>
                <van-radio name="true_false">判断题</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          
          <!-- 选择题选项 -->
          <template v-if="questionForm.type === 'choice'">
            <van-field name="isMultiple" label="是否多选">
              <template #input>
                <van-switch v-model="questionForm.isMultiple" size="20" />
              </template>
            </van-field>
            
            <div v-for="(option, index) in questionForm.options" :key="index" class="option-field">
              <van-field
                v-model="questionForm.options[index]"
                :name="`option-${index}`"
                :label="`选项${String.fromCharCode(65 + index)}`"
                placeholder="请输入选项内容"
              >
                <template #button>
                  <van-button 
                    v-if="index === questionForm.options.length - 1" 
                    size="small" 
                    type="primary" 
                    @click="addOption"
                  >
                    添加
                  </van-button>
                  <van-button 
                    v-else 
                    size="small" 
                    type="danger" 
                    @click="removeOption(index)"
                  >
                    删除
                  </van-button>
                </template>
              </van-field>
            </div>
            
            <van-field name="answer" label="正确答案">
              <template #input>
                <template v-if="questionForm.isMultiple">
                  <van-checkbox-group v-model="questionForm.answer" direction="horizontal">
                    <van-checkbox 
                      v-for="(_, index) in questionForm.options" 
                      :key="index" 
                      :name="index.toString()"
                    >
                      {{ String.fromCharCode(65 + index) }}
                    </van-checkbox>
                  </van-checkbox-group>
                </template>
                <template v-else>
                <van-radio-group v-model="questionForm.answer" direction="horizontal">
                  <van-radio 
                    v-for="(_, index) in questionForm.options" 
                    :key="index" 
                    :name="index.toString()"
                  >
                    {{ String.fromCharCode(65 + index) }}
                  </van-radio>
                </van-radio-group>
              </template>
            </template>
          </van-field>
        </template>
        
        <!-- 填空题答案 -->
        <template v-if="questionForm.type === 'text'">
          <van-field
            v-model="questionForm.answer"
            name="text-answer"
            label="正确答案"
            type="textarea"
            rows="2"
            placeholder="请输入正确答案"
          />
        </template>
        
        <!-- 判断题答案 -->
        <template v-if="questionForm.type === 'true_false'">
          <van-field name="true-false-answer" label="正确答案">
            <template #input>
              <van-radio-group v-model="questionForm.answer" direction="horizontal">
                <van-radio :name="true">正确</van-radio>
                <van-radio :name="false">错误</van-radio>
              </van-radio-group>
            </template>
          </van-field>
        </template>
      </van-form>
    </van-dialog>
    
    <!-- 删除题目确认弹窗 -->
    <van-dialog
      v-model:show="showDeleteConfirm"
      title="确认删除"
      show-cancel-button
      @confirm="deleteQuestion"
    >
      <p style="padding: 20px 16px;">确定要删除该题目吗？该操作不可撤销。</p>
    </van-dialog>
    
    <div class="action-buttons">
      <van-button block type="primary" @click="saveExam">保存考试</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast, showSuccessToast } from 'vant';
import YHeader from '@/components/YHeader.vue';

interface Exam {
  id: string;
  title: string;
  description: string;
  startTime: string;
  endTime: string;
  totalScore: number;
  allowRetake: boolean;
  status: 'not_started' | 'in_progress' | 'finished';
}

interface Question {
  id: string;
  title: string;
  type: 'choice' | 'text' | 'true_false';
  score: number;
  options?: string[];
  isMultiple?: boolean;
  answer: string | string[] | boolean;
}

const router = useRouter();
const route = useRoute();
const courseId = computed(() => route.query.courseId as string);
const examId = computed(() => route.query.examId as string);

// 模拟数据 - 实际应该从API获取
const exam = ref<Exam>({
  id: '1',
  title: '期中考试：Vue基础',
  description: 'Vue3组件、生命周期和响应式原理',
  startTime: '2023-11-10T09:00:00',
  endTime: '2023-11-10T11:00:00',
  totalScore: 100,
  allowRetake: false,
  status: 'not_started'
});

const questions = ref<Question[]>([
  {
    id: '1',
    title: 'Vue3中，哪个API用于创建响应式对象？',
    type: 'choice',
    score: 10,
    options: ['reactive', 'ref', 'computed', '以上都是'],
    isMultiple: true,
    answer: ['0', '1', '2']
  },
  {
    id: '2',
    title: 'Vue3的组合式API的主要入口函数是什么？',
    type: 'choice',
    score: 10,
    options: ['setup', 'created', 'mounted', 'onMounted'],
    isMultiple: false,
    answer: '0'
  },
  {
    id: '3',
    title: 'Vue3完全兼容Vue2的所有特性。',
    type: 'true_false',
    score: 5,
    answer: false
  },
  {
    id: '4',
    title: '请简述Vue3中ref和reactive的区别。',
    type: 'text',
    score: 15,
    answer: 'ref用于基本类型数据的响应式，也可以用于对象，但需要通过.value访问；reactive用于对象类型的响应式，不能用于基本类型。'
  }
]);

const showCreateQuestion = ref(false);
const showDeleteConfirm = ref(false);
const isEditingQuestion = ref(false);
const questionToDelete = ref<Question | null>(null);

// 默认题目表单
const defaultQuestionForm = {
  id: '',
  title: '',
  type: 'choice' as 'choice' | 'text' | 'true_false',
  score: 10,
  options: ['', ''],
  isMultiple: false,
  answer: '0'
};

const questionForm = ref({ ...defaultQuestionForm });

// 监听题目类型变化重置答案
watch(() => questionForm.value.type, (newType) => {
  if (newType === 'choice') {
    questionForm.value.answer = questionForm.value.isMultiple ? [] : '0';
  } else if (newType === 'text') {
    questionForm.value.answer = '';
  } else if (newType === 'true_false') {
    questionForm.value.answer = true;
  }
});

onMounted(async () => {
  // 实际项目中这里应该调用API获取考试和题目数据
  // if (courseId.value && examId.value) {
  //   try {
  //     const examRes = await getExamDetail(examId.value);
  //     exam.value = examRes.data;
  //     
  //     const questionsRes = await getExamQuestions(examId.value);
  //     questions.value = questionsRes.data;
  //   } catch (error) {
  //     console.error('获取数据失败', error);
  //   }
  // }
});

const onBack = () => {
  router.back();
};

const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

const getStatusTagType = (status: string) => {
  switch (status) {
    case 'not_started': return 'primary';
    case 'in_progress': return 'warning';
    case 'finished': return 'success';
    default: return 'default';
  }
};

const getStatusText = (status: string) => {
  switch (status) {
    case 'not_started': return '未开始';
    case 'in_progress': return '进行中';
    case 'finished': return '已结束';
    default: return '未知';
  }
};

const getQuestionTypeText = (type: string) => {
  switch (type) {
    case 'choice': return '选择题';
    case 'text': return '填空题';
    case 'true_false': return '判断题';
    default: return '未知';
  }
};

const resetQuestionForm = () => {
  questionForm.value = { ...defaultQuestionForm };
  isEditingQuestion.value = false;
};

const addOption = () => {
  questionForm.value.options.push('');
};

const removeOption = (index: number) => {
  questionForm.value.options.splice(index, 1);
  
  // 更新答案
  if (questionForm.value.isMultiple) {
    const answerArray = questionForm.value.answer as string[];
    // 移除被删除的选项
    const filteredAnswer = answerArray.filter(ans => Number(ans) !== index)
      .map(ans => {
        const ansNum = Number(ans);
        // 对大于被删除索引的答案索引减1
        return ansNum > index ? String(ansNum - 1) : ans;
      });
    questionForm.value.answer = filteredAnswer;
  } else {
    const answerNum = Number(questionForm.value.answer);
    if (answerNum === index) {
      // 如果删除的是正确答案，重置为第一个选项
      questionForm.value.answer = '0';
    } else if (answerNum > index) {
      // 对大于被删除索引的答案索引减1
      questionForm.value.answer = String(answerNum - 1);
    }
  }
};

const editQuestion = (question: Question) => {
  isEditingQuestion.value = true;
  
  // 深拷贝题目数据
  questionForm.value = JSON.parse(JSON.stringify(question));
  
  // 确保选择题至少有两个选项
  if (question.type === 'choice' && (!question.options || question.options.length < 2)) {
    questionForm.value.options = ['', ''];
  }
  
  showCreateQuestion.value = true;
};

const confirmDeleteQuestion = (question: Question) => {
  questionToDelete.value = question;
  showDeleteConfirm.value = true;
};

const deleteQuestion = () => {
  if (!questionToDelete.value) return;
  
  // 从题目列表中删除
  questions.value = questions.value.filter(q => q.id !== questionToDelete.value?.id);
  showSuccessToast('题目已删除');
  
  // 更新考试总分
  updateTotalScore();
};

const validateQuestionForm = () => {
  if (!questionForm.value.title) {
    showToast('请输入题目内容');
    return false;
  }
  
  if (questionForm.value.score <= 0) {
    showToast('分值必须大于0');
    return false;
  }
  
  if (questionForm.value.type === 'choice') {
    // 验证选项
    for (let i = 0; i < questionForm.value.options.length; i++) {
      if (!questionForm.value.options[i]) {
        showToast(`选项${String.fromCharCode(65 + i)}不能为空`);
        return false;
      }
    }
    
    // 验证答案
    if (questionForm.value.isMultiple) {
      const answers = questionForm.value.answer as string[];
      if (!answers || answers.length === 0) {
        showToast('请选择至少一个正确答案');
        return false;
      }
    } else {
      if (questionForm.value.answer === '') {
        showToast('请选择正确答案');
        return false;
      }
    }
  } else if (questionForm.value.type === 'text') {
    if (!questionForm.value.answer) {
      showToast('请输入正确答案');
      return false;
    }
  }
  
  return true;
};

const saveQuestion = () => {
  if (!validateQuestionForm()) return;
  
  if (isEditingQuestion.value) {
    // 更新现有题目
    const index = questions.value.findIndex(q => q.id === questionForm.value.id);
    if (index !== -1) {
      questions.value[index] = { ...questionForm.value };
    }
  } else {
    // 添加新题目
    const newId = String(Date.now());
    questions.value.push({
      ...questionForm.value,
      id: newId
    });
  }
  
  // 重置表单
  resetQuestionForm();
  
  // 更新考试总分
  updateTotalScore();
  
  showSuccessToast(isEditingQuestion.value ? '题目已更新' : '题目已添加');
};

const updateTotalScore = () => {
  const totalScore = questions.value.reduce((sum, question) => sum + question.score, 0);
  exam.value.totalScore = totalScore;
};

const saveExam = async () => {
  if (questions.value.length === 0) {
    showToast('请至少添加一个题目');
    return;
  }
  
  // 实际项目中这里应该调用API保存考试和题目
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    showSuccessToast('考试保存成功');
    
    // 返回考试列表
    router.push({
      path: '/classroom/manage/exams',
      query: { courseId: courseId.value }
    });
  } catch (error) {
    console.error('保存考试失败', error);
    showToast('保存失败');
  }
};
</script>

<style scoped>
.exam-detail {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 80px;
}

.exam-info {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 16px;
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.exam-header h3 {
  margin: 0;
  font-size: 18px;
}

.exam-meta {
  margin-bottom: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  color: #646566;
  font-size: 14px;
  margin-bottom: 8px;
}

.meta-item .van-icon {
  margin-right: 8px;
  font-size: 16px;
}

.exam-description {
  color: #646566;
  font-size: 14px;
  line-height: 1.5;
  border-top: 1px solid #ebedf0;
  padding-top: 12px;
}

.section-divider {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px;
}

.divider-title {
  font-size: 16px;
  font-weight: 500;
}

.question-list {
  margin-bottom: 16px;
}

.question-list .van-swipe-cell {
  margin-bottom: 12px;
}

.question-type {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
}

.question-score {
  color: #ff976a;
  font-size: 14px;
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
}

.option-label {
  margin-right: 8px;
  font-weight: 500;
}

.option-content {
  flex: 1;
}

.option-field {
  position: relative;
}

.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}
</style>